using System;
using System.Text;

namespace BoxBinary.AspectCache.Core.CacheManagement
{
    /// <summary>
    /// Contains helper methods for generating short, unique cache keys for objects.
    /// </summary>
    public static class CacheKeyBuilder
    {
        public const string KeySuffix = "CM_{0}";

        /// <summary>
        /// Generates a cache key by utilising the <see cref="ICacheable.CacheKeyUniqueParams"/> property of <paramref name="fromObject"/>.
        /// </summary>
        /// <param name="fromObject"></param>
        /// <returns></returns>
        public static string GetKey(ICacheable fromObject)
        {
            #region Validate

            if (fromObject == null)
                throw new ArgumentNullException("fromObject");
            if (fromObject.CacheKeyUniqueParams == null)
                throw new ArgumentException("fromObject.CacheKeyUniqueParams");

            #endregion

            Type fromType = fromObject.GetType();

            if (fromType == typeof (CacheItemWrapper))
                fromType = ((CacheItemWrapper) fromObject).Item.GetType();

            return GetKey(fromType, fromObject.CacheKeyUniqueParams);
        }

        /// <summary>
        /// Generates a cache key from the <see cref="Type.FullName"/> of the <paramref name="objectType"/>
        /// combined with the strings provided in <paramref name="cacheKeyParams"/>.
        /// </summary>
        /// <param name="objectType"></param>
        /// <param name="cacheKeyParams"></param>
        /// <returns></returns>
        public static string GetKey(Type objectType, CacheKeyParamsCollection cacheKeyParams)
        {
            var sb = new StringBuilder();
            sb.Append(objectType.FullName);
            sb.Append(':');

            Array.Sort(cacheKeyParams.Pairs, new CacheKeyUniqueParamsComparer());

            foreach (var kValue in cacheKeyParams)
                sb.AppendFormat("{0}|{1}/", kValue.Key, kValue.Value);

            return string.Format(KeySuffix, sb.ToString().GetHashCode()).ToLower();
        }
    }
}